import pygame
from datetime import datetime, timedelta
from models import Team, Match, Message
# 颜色常量
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
GRAY = (200, 200, 200)
LIGHT_GRAY = (240, 240, 240)
DARK_GRAY = (100, 100, 100)

# 屏幕尺寸常量
SCREEN_WIDTH = 1024
SCREEN_HEIGHT = 768

class GameUI:
    def __init__(self, screen, font, small_font, large_font):
        self.screen = screen
        self.font = font
        self.small_font = small_font
        self.large_font = large_font
        # 强制初始化这些属性，确保它们被创建
        setattr(self, 'fixtures_start_index', 0)
        setattr(self, 'fixtures_dragging', False)
    def get_stage_name(self, stage):
        """获取阶段对应的名称"""
        if stage == 1:
            return "假B城市足协"
        elif stage == 2:
            return "假B俱乐部"
        elif stage == 3:
            return "种超俱乐部"
        else:
            return f"阶段 {stage}"
    def draw_main_screen(self, game):
        """绘制主界面"""
        self.screen.fill(WHITE)

        # 顶部信息栏
        pygame.draw.rect(self.screen, BLUE, (0, 0, SCREEN_WIDTH, 60))
        date_text = self.font.render(f"{game.current_date.year}年{game.current_date.month}月{game.current_date.day}日", True, WHITE)
        stage_name = self.get_stage_name(game.stage)
        stage_text = self.font.render(stage_name, True, WHITE)
        year_text = self.font.render(f"第{game.year}年", True, WHITE)
        balance_text = self.font.render(f"余额: {game.user_team.balance}元", True, WHITE)

        self.screen.blit(date_text, (20, 15))
        self.screen.blit(stage_text, (300, 15))
        self.screen.blit(year_text, (500, 15))
        self.screen.blit(balance_text, (800, 15))

        # 阶段目标
        target_y = 80
        target_text = self.large_font.render("阶段目标", True, BLACK)
        self.screen.blit(target_text, (20, target_y))

        target_y += 40
        if game.stage == 1:
            targets = ["1. 获得领导认可", "2. 连续两个赛季排名前三"]
        elif game.stage == 2:
            targets = ["1. 获得联赛冠军", "2. 完成3次假球任务"]
        else:
            targets = ["1. 保持联赛领先地位", "2. 应对金元足球挑战"]

        for target in targets:
            self.screen.blit(self.font.render(target, True, BLACK), (40, target_y))
            target_y += 30

        # 功能按钮
        buttons = []
        button_labels = ["消息", "参赛", "队员信息", "积分信息", "赛程信息"]
        button_y = 300

        for i, label in enumerate(button_labels):
            button = pygame.Rect(40 + i * 180, button_y, 160, 50)
            pygame.draw.rect(self.screen, BLUE, button)
            text = self.font.render(label, True, WHITE)
            self.screen.blit(text, (button.centerx - text.get_width()//2, button.centery - text.get_height()//2))
            buttons.append(button)

        # 球队状态
        status_y = 400
        status_text = self.large_font.render("球队状态", True, BLACK)
        self.screen.blit(status_text, (20, status_y))

        status_y += 40
        team_status = [
            f"球队: {game.user_team.name}",
            f"当前排名: 第{game.get_ranking().index(game.user_team) + 1}名",
            f"积分: {game.user_team.points}",
            f"已完成假球任务: {game.fake_mission_count}/3"
        ]

        for status in team_status:
            self.screen.blit(self.font.render(status, True, BLACK), (40, status_y))
            status_y += 30

        # 显示最新消息提示
        unread_count = sum(1 for msg in game.messages if not msg.read)
        if unread_count > 0:
            msg_hint = self.small_font.render(f"有{unread_count}条未读消息", True, RED)
            self.screen.blit(msg_hint, (40, SCREEN_HEIGHT - 30))

        return buttons
    def wrap_text(self, font, text, max_width):
        """将文本按指定宽度自动换行"""
        paragraphs = text.split('\n')
        lines = []
        for para in paragraphs:
            # 对每个段落进行自动换行处理
            words = para.split(' ')
            if not words:
                lines.append('')  # 保留空行
                continue
            
            current_line = words[0]
            for word in words[1:]:
                test_line = current_line + ' ' + word
                test_width, _ = font.size(test_line)
                
                if test_width <= max_width:
                    current_line = test_line
                else:
                    lines.append(current_line)
                    current_line = word
            lines.append(current_line)
        return lines
    def draw_message_screen(self, game):
        """绘制消息界面"""
        self.screen.fill(WHITE)

        # 返回按钮
        back_button = pygame.Rect(20, 20, 100, 40)
        pygame.draw.rect(self.screen, BLUE, back_button)
        back_text = self.font.render("返回", True, WHITE)
        self.screen.blit(back_text, (back_button.centerx - back_text.get_width()//2, 
                               back_button.centery - back_text.get_height()//2))

        # 标题
        title = self.large_font.render("消息中心", True, BLACK)
        self.screen.blit(title, (SCREEN_WIDTH//2 - title.get_width()//2, 20))

        # 显示消息列表
        y_pos = 80
        max_text_width = SCREEN_WIDTH - 80  # 减去左右边距
        
        for msg in reversed(game.messages):
            # 未读消息用特殊颜色
            color = RED if not msg.read else BLACK
            msg_text = str(msg)
            
            # 将长文本自动换行
            wrapped_lines = self.wrap_text(self.small_font, msg_text, max_text_width)
            
            # 绘制多行文本
            for line in wrapped_lines:
                text_surface = self.small_font.render(line, True, color)
                self.screen.blit(text_surface, (40, y_pos))
                y_pos += self.small_font.get_height() + 5  # 行间距
            
            y_pos += 15  # 消息之间的间距
            
            # 超出屏幕范围则停止绘制
            if y_pos > SCREEN_HEIGHT - 40:
                break

        return back_button
    def draw_season_summary_screen(self, game):
        """绘制赛季总结页面"""
        self.screen.fill(WHITE)

        # 返回按钮
        back_button = pygame.Rect(SCREEN_WIDTH - 120, SCREEN_HEIGHT - 60, 100, 40)
        pygame.draw.rect(self.screen, BLUE, back_button)
        back_text = self.font.render("继续", True, WHITE)
        self.screen.blit(back_text, (
            back_button.centerx - back_text.get_width()//2,
            back_button.centery - back_text.get_height()//2
        ))

        # 标题
        title = self.large_font.render(f"{game.year}赛季总结", True, BLACK)
        self.screen.blit(title, (SCREEN_WIDTH//2 - title.get_width()//2, 20))

        # 年度任务完成情况
        task_y = 80
        task_title = self.font.render("年度任务完成情况", True, BLACK)
        self.screen.blit(task_title, (40, task_y))

        task_y += 30
        tasks = game.check_annual_tasks()
        for task in tasks:
            status = "✓ 已完成" if task['completed'] else "✗ 未完成"
            status_color = GREEN if task['completed'] else RED
            task_text = self.font.render(f"• {task['description']}", True, BLACK)
            status_text = self.font.render(status, True, status_color)
            self.screen.blit(task_text, (60, task_y))
            self.screen.blit(status_text, (400, task_y))
            task_y += 30

        # 积分榜标题
        standings_y = task_y + 20
        standings_title = self.font.render("赛季积分榜", True, BLACK)
        self.screen.blit(standings_title, (40, standings_y))

        # 绘制积分榜（复用现有逻辑）
        standings_y += 30
        sorted_teams = game.get_ranking(
            use_head_goals=((game.stage == 1 and game.year >= 4) or (game.stage >= 2)),
            use_two_year_points=(game.stage >= 2 and game.year >= 4)
        )

        headers = ["排名", "球队", "场次", "积分", "净胜球"]
        x_positions = [40, 100, 300, 360, 420]
        if (game.stage == 1 and game.year >= 4) or (game.stage >= 2):
            headers.append("头球")
            x_positions.append(490)

        # 绘制表头
        for i, header in enumerate(headers):
            text = self.small_font.render(header, True, BLACK)
            self.screen.blit(text, (x_positions[i], standings_y))

        standings_y += 25
        # 绘制前6名球队数据
        for i, team in enumerate(sorted_teams[:6]):
            color = RED if team == game.user_team else BLACK
            self.screen.blit(self.small_font.render(str(i+1), True, color), (x_positions[0], standings_y))
            self.screen.blit(self.small_font.render(team.name, True, color), (x_positions[1], standings_y))
            self.screen.blit(self.small_font.render(str(team.matches_played), True, color), (x_positions[2], standings_y))
            self.screen.blit(self.small_font.render(str(team.points), True, color), (x_positions[3], standings_y))
            self.screen.blit(self.small_font.render(str(team.calculate_goal_difference()), True, color), (x_positions[4], standings_y))
            if len(x_positions) > 5:
                self.screen.blit(self.small_font.render(str(team.head_goals), True, color), (x_positions[5], standings_y))
            standings_y += 20

        # 绘制游戏结束提示
        if game.game_over:
            end_text = self.large_font.render(game.ending, True, (200, 0, 0))
            text_rect = end_text.get_rect(center=(SCREEN_WIDTH//2, SCREEN_HEIGHT//2 + 100))
            # 添加半透明遮罩
            s = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.SRCALPHA)
            s.fill((255, 255, 255, 180))
            self.screen.blit(s, (0, 0))
            self.screen.blit(end_text, text_rect)

        return back_button
    def draw_team_info_screen(self, game):
        """绘制球队信息界面"""
        self.screen.fill(WHITE)

        # 返回按钮
        back_button = pygame.Rect(20, 20, 100, 40)
        pygame.draw.rect(self.screen, BLUE, back_button)
        back_text = self.font.render("返回", True, WHITE)
        self.screen.blit(back_text, (back_button.centerx - back_text.get_width()//2, 
                               back_button.centery - back_text.get_height()//2))

        # 标题
        title = self.large_font.render(f"{game.user_team.name} 球员信息", True, BLACK)
        self.screen.blit(title, (SCREEN_WIDTH//2 - title.get_width()//2, 20))

        # 球员列表
        y_pos = 80
        for player in game.user_team.players:
            # 高亮显示体力不足的球员
            color = RED if player.stamina <= 3 else BLACK
            player_text = self.font.render(f"{player.name} - 能力: {player.ability}, 体力: {player.stamina}", True, color)
            bio_text = self.small_font.render(f"简介: {player.bio}", True, BLACK)

            self.screen.blit(player_text, (40, y_pos))
            self.screen.blit(bio_text, (40, y_pos + 30))
            y_pos += 70
            if y_pos > SCREEN_HEIGHT - 40:
                break

        return back_button

    def draw_standings_screen(self, game):
        """绘制积分榜界面"""
        self.screen.fill(WHITE)

        # 返回按钮
        back_button = pygame.Rect(20, 20, 100, 40)
        pygame.draw.rect(self.screen, BLUE, back_button)
        back_text = self.font.render("返回", True, WHITE)
        self.screen.blit(back_text, (back_button.centerx - back_text.get_width()//2, 
                               back_button.centery - back_text.get_height()//2))

        # 标题
        title = self.large_font.render("积分榜", True, BLACK)
        self.screen.blit(title, (SCREEN_WIDTH//2 - title.get_width()//2, 20))

        # 排序球队
        sorted_teams = game.get_ranking(
            use_head_goals=((game.stage == 1 and game.year >= 4) or (game.stage >= 2)),
            use_two_year_points=(game.stage >= 2 and game.year >= 4)
        )

        # 表头
        headers = ["排名", "球队", "场数", "积分", "进球", "失球", "净胜球"]
        if (game.stage == 1 and game.year >= 4) or (game.stage >= 2):
            headers.append("头球")
        if game.stage >= 2 and game.year >= 4:
            headers.append("中超积分")

        x_positions = [40, 80, 300, 360, 420, 480, 550]
        if (game.stage == 1 and game.year >= 4) or (game.stage >= 2):
            x_positions.append(620)
        if game.stage >= 2 and game.year >= 4:
            x_positions.append(700)

        y_pos = 80
        for i, header in enumerate(headers):
            text = self.small_font.render(header, True, BLACK)
            self.screen.blit(text, (x_positions[i], y_pos))

        y_pos += 30

        # 积分数据
        for i, team in enumerate(sorted_teams):
            # 高亮显示用户球队
            color = RED if team == game.user_team else BLACK

            # 排名
            rank_text = self.small_font.render(str(i+1), True, color)
            self.screen.blit(rank_text, (x_positions[0], y_pos))

            # 球队名称
            name_text = self.small_font.render(team.name, True, color)
            self.screen.blit(name_text, (x_positions[1], y_pos))

            # 场次
            mp_text = self.small_font.render(str(team.matches_played), True, color)
            self.screen.blit(mp_text, (x_positions[2], y_pos))

            # 积分
            points_text = self.small_font.render(str(team.points), True, color)
            self.screen.blit(points_text, (x_positions[3], y_pos))

            # 进球
            gs_text = self.small_font.render(str(team.goals_scored), True, color)
            self.screen.blit(gs_text, (x_positions[4], y_pos))

            # 失球
            gc_text = self.small_font.render(str(team.goals_conceded), True, color)
            self.screen.blit(gc_text, (x_positions[5], y_pos))

            # 净胜球
            gd_text = self.small_font.render(str(team.calculate_goal_difference()), True, color)
            self.screen.blit(gd_text, (x_positions[6], y_pos))

            # 头球
            if (game.stage == 1 and game.year >= 4) or (game.stage >= 2):
                hg_text = self.small_font.render(str(team.head_goals), True, color)
                self.screen.blit(hg_text, (x_positions[7], y_pos))

            # 中超积分
            if game.stage >= 2 and game.year >= 4:
                csl_points = team.points + team.last_year_points
                csl_text = self.small_font.render(str(csl_points), True, color)
                self.screen.blit(csl_text, (x_positions[-1], y_pos))

            y_pos += 25
            if y_pos > SCREEN_HEIGHT - 40:
                break

        return back_button

    def draw_fixtures_screen(self, game):
        """绘制赛程界面，显示赛季计划表"""
        self.screen.fill(WHITE)

        # 返回按钮
        back_button = pygame.Rect(20, 20, 100, 40)
        pygame.draw.rect(self.screen, BLUE, back_button)
        back_text = self.font.render("返回", True, WHITE)
        self.screen.blit(back_text, (back_button.centerx - back_text.get_width()//2, 
                               back_button.centery - back_text.get_height()//2))

        # 标题
        title = self.large_font.render(f"{game.current_date.year}赛季赛程表", True, BLACK)
        self.screen.blit(title, (SCREEN_WIDTH//2 - title.get_width()//2, 20))

        # 表头
        headers = ["场次", "主队", "比分", "客队", "状态"]
        x_positions = [40, 100, 450, 520, 800]

        y_pos = 80
        for i, header in enumerate(headers):
            text = self.small_font.render(header, True, BLACK)
            self.screen.blit(text, (x_positions[i], y_pos))

        y_pos += 30

        # 显示赛程表内容，支持滚动查看
        # 只显示当前可见区域的比赛
        visible_matches = 20  # 一屏可显示的比赛数量
        total_matches = len(game.season_schedule)
        start_index = self.fixtures_start_index

        # 确保start_index在有效范围内
        start_index = max(0, min(start_index, max(0, total_matches - visible_matches)))

        # 滚动区域和滚动条设置
        scroll_area_height = visible_matches * 25
        scroll_area_y = y_pos
        scroll_bar_width = 15
        scroll_bar_x = SCREEN_WIDTH - scroll_bar_width - 20
        scroll_bar_bg_height = scroll_area_height
        scroll_bar_bg = pygame.Rect(scroll_bar_x, scroll_area_y, scroll_bar_width, scroll_bar_bg_height)

        # 滚动滑块高度和位置
        if total_matches > visible_matches:
            slider_height = max(30, int(scroll_area_height * visible_matches / total_matches))
            slider_max_y = scroll_area_y + scroll_area_height - slider_height
            slider_y = scroll_area_y + int((scroll_area_height - slider_height) * start_index / (total_matches - visible_matches))
            scroll_slider = pygame.Rect(scroll_bar_x, slider_y, scroll_bar_width, slider_height)
        else:
            # 比赛数量不足一屏，不需要滚动条
            scroll_slider = None
            start_index = 0
            self.fixtures_start_index = 0

        # 检查滚动事件
        mouse_pressed = pygame.mouse.get_pressed()
        mouse_pos = pygame.mouse.get_pos()

        for event in pygame.event.get():
            if event.type == pygame.MOUSEWHEEL and total_matches > visible_matches:
                # 鼠标滚轮滚动
                if event.y < 0 and start_index < total_matches - visible_matches:
                    start_index += 1
                elif event.y > 0 and start_index > 0:
                    start_index -= 1
                # 更新滑块位置和成员变量
                slider_y = scroll_area_y + int((scroll_area_height - slider_height) * start_index / (total_matches - visible_matches))
                scroll_slider.y = slider_y
                self.fixtures_start_index = start_index
            elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1 and total_matches > visible_matches:
                # 鼠标左键点击
                mouse_pos = event.pos
                if scroll_slider.collidepoint(mouse_pos):
                    # 点击滑块，开始拖动
                    self.fixtures_dragging = True
                elif scroll_bar_bg.collidepoint(mouse_pos):
                    # 点击滚动条背景，跳转位置
                    click_y = mouse_pos[1] - scroll_area_y
                    ratio = click_y / scroll_area_height
                    start_index = int(ratio * (total_matches - visible_matches))
                    start_index = max(0, min(start_index, total_matches - visible_matches))
                    # 更新滑块位置和成员变量
                    slider_y = scroll_area_y + int((scroll_area_height - slider_height) * start_index / (total_matches - visible_matches))
                    scroll_slider.y = slider_y
                    self.fixtures_start_index = start_index
            elif event.type == pygame.MOUSEMOTION and total_matches > visible_matches:
                # 拖动滑块
                if mouse_pressed[0] and self.fixtures_dragging:
                    mouse_pos = event.pos
                    new_y = mouse_pos[1] - slider_height // 2
                    new_y = max(scroll_area_y, min(new_y, slider_max_y))
                    scroll_slider.y = new_y
                    # 更新start_index和成员变量
                    ratio = (new_y - scroll_area_y) / (scroll_area_height - slider_height)
                    start_index = int(ratio * (total_matches - visible_matches))
                    start_index = max(0, min(start_index, total_matches - visible_matches))
                    self.fixtures_start_index = start_index
            elif event.type == pygame.MOUSEBUTTONUP and event.button == 1:
                # 释放鼠标，结束拖动
                self.fixtures_dragging = False

        # 绘制滚动区域背景
        pygame.draw.rect(self.screen, LIGHT_GRAY, (x_positions[0], scroll_area_y, SCREEN_WIDTH - x_positions[0] - scroll_bar_width - 30, scroll_area_height))

        # 显示比赛
        for i in range(start_index, min(start_index + visible_matches, total_matches)):
            match = game.season_schedule[i]

            # 高亮显示用户参与的比赛
            color = RED if match.is_user_involved else BLACK

            # 场次
            num_text = self.small_font.render(str(match.match_count), True, color)
            self.screen.blit(num_text, (x_positions[0], y_pos))

            # 主队
            home_text = self.small_font.render(match.home_team.name, True, color)
            self.screen.blit(home_text, (x_positions[1], y_pos))

            # 比分
            if match.completed:
                score_text = self.small_font.render(f"{match.home_goals} : {match.away_goals}", True, color)
            else:
                score_text = self.small_font.render("vs", True, color)
            self.screen.blit(score_text, (x_positions[2], y_pos))

            # 客队
            away_text = self.small_font.render(match.away_team.name, True, color)
            self.screen.blit(away_text, (x_positions[3], y_pos))

            # 状态
            if match.completed:
                status = "已完成"
            else:
                status = "待进行" if i == start_index else "即将进行"

            status_text = self.small_font.render(status, True, color)
            self.screen.blit(status_text, (x_positions[4], y_pos))

            y_pos += 25

        # 绘制滚动条
        if total_matches > visible_matches:
            # 绘制滚动条背景
            pygame.draw.rect(self.screen, GRAY, scroll_bar_bg)
            # 绘制滚动滑块
            pygame.draw.rect(self.screen, DARK_GRAY, scroll_slider)
            # 显示滚动提示
            scroll_hint = self.small_font.render("使用鼠标滚轮或拖动滚动条查看更多比赛", True, DARK_GRAY)
            self.screen.blit(scroll_hint, (SCREEN_WIDTH//2 - scroll_hint.get_width()//2, SCREEN_HEIGHT - 40))

        return back_button

    def draw_match_setup_screen(self, game):
        """绘制比赛设置界面"""
        self.screen.fill(WHITE)

        # 返回按钮
        back_button = pygame.Rect(20, 20, 100, 40)
        pygame.draw.rect(self.screen, BLUE, back_button)
        back_text = self.font.render("返回", True, WHITE)
        self.screen.blit(back_text, (back_button.centerx - back_text.get_width()//2, 
                               back_button.centery - back_text.get_height()//2))

        # 获取下一场比赛
        if not game.current_match:
            game.current_match = game.get_next_user_match()

        if not game.current_match:
            # 没有比赛可进行
            text = self.font.render("本赛季所有比赛已完成！", True, BLACK)
            self.screen.blit(text, (SCREEN_WIDTH//2 - text.get_width()//2, SCREEN_HEIGHT//2))
            # 返回包含back键的字典，而不是直接返回back_button
            return {"back": back_button}

        # 标题
        home_away = "主场" if game.current_match.home_team == game.user_team else "客场"
        title = self.large_font.render(f"第{game.current_match.match_count}场 - {home_away} vs {game.current_match.away_team.name if game.current_match.home_team == game.user_team else game.current_match.home_team.name}", True, BLACK)
        self.screen.blit(title, (SCREEN_WIDTH//2 - title.get_width()//2, 20))

        # 检查是否触发假球任务
        if game.must_lose is False:
            game.must_lose = game.handle_fake_mission(game.current_match)

        # 显示假球任务提示
        if game.must_lose:
            mission_text = self.font.render("⚠️ 足协任务：本场需要让对方获胜 ⚠️", True, RED)
            self.screen.blit(mission_text, (SCREEN_WIDTH//2 - mission_text.get_width()//2, 70))

        # 本队信息
        pygame.draw.rect(self.screen, LIGHT_GRAY, (40, 120, 460, 300))
        team_title = self.font.render(f"{game.user_team.name} 球员", True, BLACK)
        self.screen.blit(team_title, (60, 140))

        y_pos = 180
        for player in game.user_team.players:
            # 球员信息
            player_text = self.small_font.render(f"{player.name} - 能力: {player.ability}, 体力: {player.stamina}", True, BLACK)
            self.screen.blit(player_text, (60, y_pos))
            y_pos += 30

        # 本队积分
        points_text = self.small_font.render(f"当前积分: {game.user_team.points}", True, BLACK)
        self.screen.blit(points_text, (60, y_pos + 20))

        # 对手信息
        opponent = game.current_match.away_team if game.current_match.home_team == game.user_team else game.current_match.home_team
        pygame.draw.rect(self.screen, LIGHT_GRAY, (520, 120, 460, 300))
        opp_title = self.font.render(f"{opponent.name} 信息", True, BLACK)
        self.screen.blit(opp_title, (540, 140))

        # 对手排名
        sorted_teams = game.get_ranking()
        opp_rank = sorted_teams.index(opponent) + 1 if opponent in sorted_teams else len(sorted_teams)
        rank_text = self.small_font.render(f"当前排名: 第{opp_rank}名", True, BLACK)
        self.screen.blit(rank_text, (540, 180))

        # 对手积分
        opp_points_text = self.small_font.render(f"当前积分: {opponent.points}", True, BLACK)
        self.screen.blit(opp_points_text, (540, 210))

        # 对手球员体力状态
        opp_stamina = sum(p.stamina for p in opponent.players) / len(opponent.players) if opponent.players else 0
        #stamina_status = "充足" if opp_stamina > 7 else "一般" if opp_stamina > 3 else "不足"
        #opp_stamina_text = self.small_font.render(f"球员体力状态: {stamina_status}", True, BLACK)
        #self.screen.blit(opp_stamina_text, (540, 240))
        # 随机生成对方球队本次比赛的体力值
        import random
        if game.year == 1:
            opp_match_stamina = random.randint(1, 3)
        else:
            opp_match_stamina = random.randint(5, 10)
        # 确保生成的体力值小于对方球队的实际体力
        #opp_match_stamina = min(opp_match_stamina, int(opp_stamina))
        # 存储到game对象中，供比赛阶段使用
        game.current_match.opponent_match_stamina = opp_match_stamina
        # 显示对方球队本次比赛的体力值
        opp_match_stamina_text = self.small_font.render(f"本次比赛体力: {opp_match_stamina}", True, BLACK)
        self.screen.blit(opp_match_stamina_text, (540, 240))
        # 历史交锋
        h2h_wins = 0
        h2h_losses = 0
        h2h_draws = 0
        for match in game.season_schedule:
            if match.is_user_involved and match.completed and \
               ((match.home_team == game.user_team and match.away_team == opponent) or \
                (match.away_team == game.user_team and match.home_team == opponent)):
                if (match.home_team == game.user_team and match.home_goals > match.away_goals) or \
                   (match.away_team == game.user_team and match.away_goals > match.home_goals):
                    h2h_wins += 1
                elif (match.home_team == game.user_team and match.home_goals < match.away_goals) or \
                     (match.away_team == game.user_team and match.away_goals < match.home_goals):
                    h2h_losses += 1
                else:
                    h2h_draws += 1

        h2h_text = self.small_font.render(f"历史交锋: 胜{h2h_wins} 平{h2h_draws} 负{h2h_losses}", True, BLACK)
        self.screen.blit(h2h_text, (540, 270))

        # 比赛设置
        pygame.draw.rect(self.screen, LIGHT_GRAY, (40, 450, 940, 150))
        setup_title = self.font.render("比赛设置", True, BLACK)
        self.screen.blit(setup_title, (60, 470))

        # 体力使用设置
        stamina_text = self.small_font.render("1. 球员体力使用:", True, BLACK)
        self.screen.blit(stamina_text, (60, 500))

        stamina_options = ["全部使用", "使用一半", "使用2点"]
        for i, option in enumerate(stamina_options):
            x = 180 + i * 200
            color = BLUE if i+1 == game.stamina_choice else GRAY
            pygame.draw.rect(self.screen, color, (x, 495, 160, 30))
            option_text = self.small_font.render(f"{i+1}) {option}", True, WHITE if i+1 == game.stamina_choice else BLACK)
            self.screen.blit(option_text, (x + 10, 498))

        # 行贿选项（第二阶段及以后）
        bribe_button = None
        if game.stage >= 2:
            bribe_text = self.small_font.render("2. 是否行贿对方球员（消耗3000元）:", True, BLACK)
            self.screen.blit(bribe_text, (60, 540))

            bribe_x = 380
            for i, option in enumerate(["是", "否"]):
                x = bribe_x + i * 100
                color = BLUE if (i == 0 and game.bribe_used) or (i == 1 and not game.bribe_used) else GRAY
                pygame.draw.rect(self.screen, color, (x, 535, 80, 30))
                option_text = self.small_font.render(option, True, WHITE if color == BLUE else BLACK)
                self.screen.blit(option_text, (x + 30, 538))
                if i == 0:
                    bribe_button = pygame.Rect(x, 535, 80, 30)
                else:
                    no_bribe_button = pygame.Rect(x, 535, 80, 30)

        # 开始比赛按钮
        start_button = pygame.Rect(420, 620, 180, 50)
        pygame.draw.rect(self.screen, GREEN, start_button)
        start_text = self.font.render("开始比赛", True, WHITE)
        self.screen.blit(start_text, (start_button.centerx - start_text.get_width()//2, 
                                start_button.centery - start_text.get_height()//2))

        # 存储按钮位置以便检测点击
        buttons = {
            "back": back_button,
            "start": start_button,
            "stamina1": pygame.Rect(180, 495, 160, 30),
            "stamina2": pygame.Rect(380, 495, 160, 30),
            "stamina3": pygame.Rect(580, 495, 160, 30)
        }

        if game.stage >= 2:
            buttons["bribe_yes"] = bribe_button
            buttons["bribe_no"] = no_bribe_button

        return buttons

    def draw_match_screen(self, game):
        """绘制比赛界面"""
        self.screen.fill(WHITE)

        # 始终显示返回按钮
        back_button = pygame.Rect(20, 20, 100, 40)
        pygame.draw.rect(self.screen, BLUE, back_button)
        back_text = self.font.render("返回", True, WHITE)
        self.screen.blit(back_text, (back_button.centerx - back_text.get_width()//2, 
                               back_button.centery - back_text.get_height()//2))

        # 标题
        if game.current_match:
            title = self.font.render(f"第{game.current_match.match_count}场: {game.current_match.home_team.name} vs {game.current_match.away_team.name}", True, BLACK)
            self.screen.blit(title, (SCREEN_WIDTH//2 - title.get_width()//2, 20))

            # 比分
            score_text = self.large_font.render(f"{game.current_match.home_goals if game.current_match.home_goals is not None else 0} : {game.current_match.away_goals if game.current_match.away_goals is not None else 0}", True, BLACK)
            self.screen.blit(score_text, (SCREEN_WIDTH//2 - score_text.get_width()//2, 70))

            # 比赛时间
            minute_text = self.font.render(f"第{game.current_match.minute}分钟" if not game.current_match.completed else "比赛结束", True, BLACK)
            self.screen.blit(minute_text, (SCREEN_WIDTH//2 - minute_text.get_width()//2, 130))

            # 比赛事件区域
            pygame.draw.rect(self.screen, LIGHT_GRAY, (40, 180, 940, 500))

            # 显示最近的15个事件
            y_pos = 200
            for event in reversed(game.current_match.events[-15:]):
                event_text = self.small_font.render(event, True, BLACK)
                self.screen.blit(event_text, (60, y_pos))
                y_pos += 30

        buttons = {}
        buttons["back"] = back_button

        return buttons

    def draw_game_over_screen(self, game):
        """绘制游戏结束界面"""
        self.screen.fill(WHITE)

        # 标题
        title = self.large_font.render("游戏结束", True, BLACK)
        self.screen.blit(title, (SCREEN_WIDTH//2 - title.get_width()//2, 100))

        # 结局
        ending_texts = []
        words = game.ending.split('，')
        for word in words:
            ending_texts.append(word)

        y_pos = 200
        for text in ending_texts:
            text_surface = self.font.render(text, True, BLACK)
            self.screen.blit(text_surface, (SCREEN_WIDTH//2 - text_surface.get_width()//2, y_pos))
            y_pos += 40

        # 重新开始按钮
        restart_button = pygame.Rect(420, 600, 180, 50)
        pygame.draw.rect(self.screen, GREEN, restart_button)
        restart_text = self.font.render("重新开始", True, WHITE)
        self.screen.blit(restart_text, (restart_button.centerx - restart_text.get_width()//2, 
                                  restart_button.centery - restart_text.get_height()//2))

        return restart_button